﻿export function init(panelId, dotNetHelper) {
    window.SORTABLE_INSTANCES ??= {};

    const panelEl = document.getElementById(panelId);

    panelEl.addEventListener('mouseover', (e) => {
        if (e.target.closest('.panel') === panelEl) {
            for (const el of document.querySelectorAll('.panel.panel-active')) {
                el.classList.remove('panel-active');
            }
            panelEl.classList.add('panel-active');
        }
    });

    panelEl.addEventListener('mouseleave', () => {
        panelEl.classList.remove('panel-active');
    });

    dispose(panelId);
    setTimeout(() => {
        window.SORTABLE_INSTANCES[panelId] = new Sortable(document.getElementById(panelId), {
            group: 'detail-view-editor',
            filter: '.ignore-elements',
            ghostClass: 'sortable-ghost',
            onAdd: function (evt) {
                if (evt.from.classList.contains('panel')) {
                    const componentId = evt.item.id?.slice(3);
                    dotNetHelper.invokeMethodAsync('MoveComponentAsync', evt.newIndex, componentId);
                } else {
                    const classList = evt.item.classList.values().toArray();
                    const propertyPath = classList.findLast(e => e.startsWith('p-path-'))?.slice(7).replace(/-/g, '.');
                    if (propertyPath) {
                        dotNetHelper.invokeMethodAsync('InsertPropertyEditorAsync', evt.newIndex, propertyPath);
                        evt.item.remove();
                    } else {
                        const componentName = classList.findLast(e => e.startsWith('tool-'))?.slice(5);
                        if (componentName) {
                            dotNetHelper.invokeMethodAsync('InsertComponentAsync', evt.newIndex, componentName);
                            evt.item.remove();
                        }
                    }
                }
            },
            onUpdate: function (evt) {
                if (evt.from.classList.contains('panel')) {
                    const componentId = evt.item.id?.slice(3);
                    dotNetHelper.invokeMethodAsync('SortComponentAsync', evt.oldIndex, evt.newIndex, componentId);
                }
            }
        });
    }, 1000);
}

export function dispose(panelId) {
    if (window.SORTABLE_INSTANCES && window.SORTABLE_INSTANCES[panelId]) {
        window.SORTABLE_INSTANCES[panelId].destroy();
        delete window.SORTABLE_INSTANCES[panelId];
    }
}